package com.jk.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jk.entity.*;
import com.jk.entity.Map;
import com.jk.mapper.ShoppingCarMapper;
import com.jk.mongodb.MongodbDao;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author 周慧茹
 * 创建时间 2018/4/11  19:13
 * 邮箱 960297232@qq.com
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @Resource
    private ShoppingCarMapper shoppingcar;

    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private MongodbDao  mongodbDao;

  /*  @Resource
    private ShoppingCarDao  shoppingcarDao;*/



    @Override
    public User query() {
        User   user  = new  User();
        user.setUserpass("444");

        return shoppingcar.querycertifId();
    }



    @Override
    public void saveShop(Order testMap) {

        mongoTemplate.insert(testMap,"t_shop");
      /*  shoppingcarDao.saveShop(testMap);
*/

    }

    @Override
    public void saveDummyorder(String  cookiewy,HashMap<String, List<Shop>> map) {

        HashMap<String, HashMap<String, List<Shop>>> maps = new HashMap<>();

        maps.put(""+cookiewy+"",map);

        DummyOrder dummyOrder = new DummyOrder();

        dummyOrder.setCookieid(cookiewy);

        dummyOrder.setDatetime(new Date());

        dummyOrder.setMaps(maps);

        mongoTemplate.insert(dummyOrder,"t_dummyOrder");
    }

    @Override
    public ResponseMessage getService(String userid,HashMap<String, List<Shop>> map,String cookiewy) {

         Identity identity = shoppingcar.getuseridByidentity(userid);
         ResponseMessage responsemessage = new ResponseMessage();
         if(identity!=null){
             DummyOrder   cookie =  mongodbDao.querycookie(cookiewy);
             if(cookie!=null){
                 HashMap<String, HashMap<String, List<Shop>>> maps = cookie.getMaps();
                 Order order = new Order();
                 HashMap<String, HashMap<String, List<Shop>>> map2 = new HashMap<>();
                 for (Iterator i = maps.keySet().iterator(); i.hasNext();) {
                  Object obj = i.next();
                  // 循环输出key 和value
                   System.out.println("key=" + obj + " value=" + maps.get(obj));
                   map2.put(""+userid+"",maps.get(obj));
                   order.setMaps(map2);
                 }
                  System.out.println("map2 = [" + map2 + "]");

                 order.setUserid(userid);

                 mongoTemplate.insert(order,"t_shop");
                 mongodbDao.removeCookie(cookiewy);

                 responsemessage.setResponseno(03);
                 responsemessage.setMessage("您之前的商品已被加入购物车");

                 return  responsemessage;

             }else{

                 Order order = new Order();
                 HashMap<String, HashMap<String, List<Shop>>> maps = new HashMap<>();

                 maps.put(""+userid+"",map);
                 order.setMaps(maps);

                 order.setUserid(userid);
                 mongoTemplate.insert(order,"t_shop");
                 responsemessage.setResponseno(01);
                 responsemessage.setMessage("已经登录成功");
                 return  responsemessage;
             }

        }else {

            responsemessage.setResponseno(02);
            responsemessage.setMessage("您还没有经过实名认证，请实名后再来");

            return  responsemessage;

        }



    }

    /**
     * 点击商品添加到购物车
     * @param shopid  商品ID
     * @param mincount 商品个数
     * @param userid  用户ID
     * @return
     */
    @Override
    public ResponseMessage ShoppingCar(String shopid, Integer mincount,String userid,String cookieid)
    {

        //根据session的用户
        // id 查询是否含有有一条订单
        Order  order =     mongodbDao.queryshopCarbuuserid(userid);
        //根据 商品id  查询对应的企业id 及名称
        ShopCar  shopcar  =  shoppingcar.queryShopByShopid(shopid);
        ResponseMessage responsemessage = new ResponseMessage();



             // 如果查询到的order d订单非等于空，说明前台传来的用户已经购买过该商品，
             if(order!=null){
                 //  MaxMap
                 HashMap<String, HashMap<String, List<Shop>>> maps1 = order.getMaps();
                 // 因为每次只会查询到一个MaxMap,所有我们只需要根据用户id 取出MinMap就可以了
                 HashMap<String, List<Shop>> stringListHashMap = maps1.get(userid);
                 // 魔法值  bb 是企业id  企业id每次查出来都只可能是一条，所有不必担心循环叠加值
                 String bb=null;
                 int  count=0;
                 //取出所有的MinMap 的Key值，也就是企业id
                 Set<String> strings = stringListHashMap.keySet();
                 //遍历所有的map Key
                 for (String string : strings) {
                     //如果所有的key中有 前台发送回来的数据
                     if(string.equals(shopcar.getCompanyid())){
                         bb=string;
                         count++;

                     }
                     //说明他购买过该企业的商品
                 }if(count>0){
                     //获得当前key中的集合
                     List<Shop> shops = stringListHashMap.get(bb);
                     Integer aa=null;
                     for (int i=0;i<shops.size();i++ )  //for循环这个商铺中所有的商品
                     {
                         //如果某个商品和新加入的商品id一致，说明加入的是同一个商品，这样只需要加这个商品的数量即可
                         if(shops.get(i).getShopid().equals(shopcar.getShopid())){
                             aa=i;  //在for循环里判断会不断地走if和else，实际上只要判断一次就够了
                         }
                     }
                     if(aa!=null){
                         //修改商品的数量
                         shops.get(aa).setShopcount( shops.get(aa).getShopcount()+mincount);

                         mongodbDao.updateMap(order.getId(),maps1);
                         responsemessage.setResponseno(00);
                         responsemessage.setMessage("之前已购买过此商品，已为您修改数量");
                         return  responsemessage;

                     }else{
                         Shop newshop = new Shop();
                         newshop.setShopid(shopcar.getShopid());
                         newshop.setShopcount(mincount);
                         newshop.setShopname(shopcar.getShopname());
                         newshop.setPrice(shopcar.getShopprice());
                         //不然就加入list集合
                         shops.add(newshop);
                         mongodbDao.updateMap(order.getId(),maps1);
                         responsemessage.setResponseno(01);
                         responsemessage.setMessage("您之前购买过该家商品，已加入");
                         return  responsemessage;
                     }


                 }else{
                     List<Shop>  list  = new ArrayList<Shop>();
                     Shop newshop2 = new Shop();
                     newshop2.setShopid(shopcar.getShopid());
                     newshop2.setShopcount(mincount);
                     newshop2.setPrice(shopcar.getShopprice());
                     newshop2.setShopname(shopcar.getShopname());
                     list.add(newshop2);
                     // 否则该企业没有购买过，MaxMap中再增加一条MinMap
                     stringListHashMap.put(""+shopcar.getCompanyid()+"",list);
                     mongodbDao.updateMap(order.getId(),maps1);
                     responsemessage.setResponseno(02);
                     responsemessage.setMessage("之前没有购买过此家商品，已加入购物车");
                     return  responsemessage;

                 }

             }else{
                 HashMap<String,List<Shop>> map  = new HashMap<>();
                 HashMap<String, HashMap<String, List<Shop>>> MaxMap = new HashMap<>();
                 Order orders = new Order();
                 orders.setUserid(userid);
                 List<Shop>  list  = new ArrayList<Shop>();
                 Shop shop = new Shop();
                 shop.setShopid(shopid);
                 shop.setShopcount(mincount);
                 shop.setShopname(shopcar.getShopname());
                 shop.setPrice(shopcar.getShopprice());
                 list.add(shop);
                 map.put(""+shopcar.getCompanyid()+"",list);
                 MaxMap.put(""+userid+"",map);
                 orders.setUserid(userid);
                 orders.setMaps(MaxMap);
                 mongoTemplate.insert(orders,"t_shop");
                 responsemessage.setResponseno(03);
                 responsemessage.setMessage("至今为止您是第一次加入购物车哟~");
                 return  responsemessage;
             }

    }

    @Override
    public ResponseMessage DummyShoppingCar(String shopid, Integer mincount,String cookiewy) {
        //根据session的用户
        // id 查询是否含有有一条订单
        DummyOrder  order =     mongodbDao.queryDummyShoppingCar(cookiewy);
        //根据 商品id  查询对应的企业id 及名称
        ShopCar  shopcar  =  shoppingcar.queryShopByShopid(shopid);
        ResponseMessage responsemessage = new ResponseMessage();
        // 如果查询到的order d订单非等于空，说明前台传来的用户已经购买过该商品，
        if(order!=null){
            //  MaxMap
            HashMap<String, HashMap<String, List<Shop>>> maps1 = order.getMaps();
            // 因为每次只会查询到一个MaxMap,所有我们只需要根据用户id 取出MinMap就可以了
            HashMap<String, List<Shop>> stringListHashMap = maps1.get(cookiewy);
            // 魔法值  bb 是企业id  企业id每次查出来都只可能是一条，所有不必担心循环叠加值
            String bb=null;
            int  count=0;
            //取出所有的MinMap 的Key值，也就是企业id
            Set<String> strings = stringListHashMap.keySet();
            //遍历所有的map Key
            for (String string : strings) {
                //如果所有的key中有 前台发送回来的数据
                if(string.equals(shopcar.getCompanyid())){
                    bb=string;
                    count++;

                }
                //说明他购买过该企业的商品
            }if(count>0){
                //获得当前key中的集合
                List<Shop> shops = stringListHashMap.get(bb);
                Integer aa=null;
                for (int i=0;i<shops.size();i++ )  //for循环这个商铺中所有的商品
                {
                    //如果某个商品和新加入的商品id一致，说明加入的是同一个商品，这样只需要加这个商品的数量即可
                    if(shops.get(i).getShopid().equals(shopcar.getShopid())){
                        aa=i;  //在for循环里判断会不断地走if和else，实际上只要判断一次就够了
                    }
                }
                if(aa!=null){
                    //修改商品的数量
                    shops.get(aa).setShopcount( shops.get(aa).getShopcount()+mincount);

                    mongodbDao.updateDummyOrder(order.getId(),maps1);
                    responsemessage.setResponseno(11);
                    responsemessage.setMessage("已为您修改数量（虚拟购物车）");
                    return  responsemessage;

                }else{
                    Shop newshop = new Shop();
                    newshop.setShopid(shopcar.getShopid());
                    newshop.setShopcount(mincount);
                    newshop.setShopname(shopcar.getShopname());
                    newshop.setPrice(shopcar.getShopprice());
                    //不然就加入list集合
                    shops.add(newshop);
                    mongodbDao.updateDummyOrder(order.getId(),maps1);
                    responsemessage.setResponseno(12);
                    responsemessage.setMessage("您之前好像加入过该商家的商品哦！（虚拟购物车）");
                    return  responsemessage;
                }

            }else{
                List<Shop>  list  = new ArrayList<Shop>();
                Shop newshop2 = new Shop();
                newshop2.setShopid(shopcar.getShopid());
                newshop2.setShopcount(mincount);
                newshop2.setPrice(shopcar.getShopprice());
                newshop2.setShopname(shopcar.getShopname());
                list.add(newshop2);
                // 否则该企业没有购买过，MaxMap中再增加一条MinMap
                stringListHashMap.put(""+shopcar.getCompanyid()+"",list);
                mongodbDao.updateDummyOrder(order.getId(),maps1);
                responsemessage.setResponseno(13);
                responsemessage.setMessage("第一次加入此企业的商品呢（虚拟购物车）");
                return  responsemessage;
            }

        }else{
            HashMap<String,List<Shop>> map  = new HashMap<>();
            HashMap<String, HashMap<String, List<Shop>>> MaxMap = new HashMap<>();

            List<Shop>  list  = new ArrayList<Shop>();
            Shop shop = new Shop();
            shop.setShopid(shopid);
            shop.setShopcount(mincount);
            shop.setShopname(shopcar.getShopname());
            shop.setPrice(shopcar.getShopprice());
            list.add(shop);
            map.put(""+shopcar.getCompanyid()+"",list);
            MaxMap.put(""+cookiewy+"",map);
            DummyOrder dummyOrder = new DummyOrder();
            dummyOrder.setCookieid(cookiewy);
            dummyOrder.setDatetime(new Date());
            dummyOrder.setMaps(MaxMap);
            mongoTemplate.insert(dummyOrder,"t_dummyOrder");
            responsemessage.setResponseno(14);
            responsemessage.setMessage("虽然是第一次加入我们的商品，希望会喜欢（虚拟购物车）");
            return  responsemessage;
        }


    }

    @Override
    public JSONObject pageShopCar(String offset, String limit) {

        long  ShopCarSum  = shoppingcar.getShopCarSum(Integer.parseInt(offset),Integer.parseInt(limit));

        List<ShopCar>  ShopCarList  = shoppingcar.getShopCarList(Integer.parseInt(offset),Integer.parseInt(limit));

        JSONObject  json  =  new JSONObject();


        json.put("total", ShopCarSum);

        json.put("rows", ShopCarList);

        return json;


    }

          @Override
        public ResponseMessage queryShopbycookie(String cookieid,String userid) {



        // id 查询是否含有有一条订单
        Order  order =     mongodbDao.queryshopCarbuuserid(userid);
        //根据 商品id  查询对应的企业id 及名称
        ResponseMessage responsemessage = new ResponseMessage();
        DummyOrder  dummyOrder =     mongodbDao.queryDummyShoppingCar(cookieid);

        //  如果说  cookie订单中有东西存在的话，证明在登录前  已经加入到或购物车，需要把当前购物车的信息，追加到真正的购物车中
        if(dummyOrder!=null){

            if(order!=null){
                //说明之前买过商品
                /*  真实用户购物车;*/
                HashMap<String, HashMap<String, List<Shop>>> maps1 = order.getMaps();
                // 因为每次只会查询到一个MaxMap,所有我们只需要根据用户id 取出MinMap就可以了
                HashMap<String, List<Shop>> useruseridMixMap = maps1.get(userid);
                Set<String> UserCompanyid = useruseridMixMap.keySet();
                /*  虚拟用户购物车;*/
                HashMap<String, HashMap<String, List<Shop>>> cookieidMaxMap = dummyOrder.getMaps();
                HashMap<String, List<Shop>> cookieidMixMap = cookieidMaxMap.get(cookieid);
                Set<String> dummyCompanyid = cookieidMixMap.keySet();
                //真实用户购物车
                String usercar=null;
                int  count=0;
                //虚拟用户购物车
                String  dummycar  =null;
                Integer  equalshop = null;
                Integer  dummyshop = null;
                String usercar2=null;

                //虚拟用户购物车
                String  dummycar2  =null;
                // 遍历真实用户购物车
                for (String user : UserCompanyid) {

                    for (String dummy : dummyCompanyid) {
                        //说明虚拟购物车中包括了 真实购物车的企业信息，
                        if(Objects.equals(user,dummy)){
                            count++;
                            usercar=user;
                            dummycar=dummy;
                        }else{
                            //说明虚拟购物车中没有包括真实购物车的企业信息，
                            dummycar2=dummy;

                        }

                    }
                }

                List<Shop> userlist = useruseridMixMap.get(usercar);
                //虚拟用户购物车里的list
                List<Shop> dummylist = cookieidMixMap.get(dummycar);
                if(count>0){
                    //真实用户购物车里的list
                    for (int i = 0; i < userlist.size(); i++) {
                        for (int j = 0; j < dummylist.size(); j++) {
                            //说明有一样的产品，那么久直接给它把当前 数量加加就可以了
                            if(Objects.equals(userlist.get(i).getShopid(),dummylist.get(i).getShopid())){

                                equalshop=i;
                                dummyshop=j;
                            }

                        }
                    }if(equalshop!=null){
                        userlist.get(equalshop).setShopcount(userlist.get(equalshop).getShopcount()+(dummylist.get(dummyshop).getShopcount()));
                        mongodbDao.updateMap(order.getId(),maps1);
                        mongodbDao.removeCookie(cookieid);
                        responsemessage.setResponseno(20);
                        responsemessage.setMessage("您是后来登录过的用户，之前的商品已经被加入购物车了呦");
                        return  responsemessage;
                    }else{


                        Shop newshop = new Shop();
                        newshop.setShopid(dummylist.get(dummyshop).getShopid());
                        newshop.setShopcount(dummylist.get(dummyshop).getShopcount());
                        newshop.setShopname(dummylist.get(dummyshop).getShopname());
                        //不然就加入list集合
                        userlist.add(newshop);
                        mongodbDao.updateMap(order.getId(),maps1);
                        mongodbDao.removeCookie(cookieid);
                    }


                }else{


                    for (String dummy : dummyCompanyid) {

                        List<Shop> dummylists = cookieidMixMap.get(dummycar);
                        Integer    dummy6  =null;

                        for (int i = 0; i < dummylists.size(); i++) {

                            useruseridMixMap.put(""+dummy+"",dummylists);
                        }

                    }

                    mongodbDao.updateMap(order.getId(),maps1);
                    mongodbDao.removeCookie(cookieid);

                }

            }else{

                HashMap<String, HashMap<String, List<Shop>>> hashmap = new HashMap<>();

                HashMap<String, HashMap<String, List<Shop>>> cookieidMaxMap = dummyOrder.getMaps();
                HashMap<String, List<Shop>> cookieidMixMap = cookieidMaxMap.get(cookieid);
                Set<String> dummyCompanyid = cookieidMixMap.keySet();
                hashmap.put(""+userid+"",cookieidMixMap);
                Order orders = new Order();
                orders.setUserid(userid);
                List<Shop>  list  = new ArrayList<Shop>();
                orders.setUserid(userid);
                orders.setMaps(hashmap);
                mongoTemplate.insert(orders,"t_shop");
                mongodbDao.removeCookie(cookieid);
            }


        }


        return null;




    }

    @Override
    public List<ShopCar> getShopCarList(int start, Integer limit) {

        List<ShopCar>  list = shoppingcar.getShopCarList(start,limit);

        return list;
    }

    @Override
    public String quercommodityByid(String shopid) {


        return shoppingcar.quercommodityByid(shopid);
    }

    @Override
    public  HashMap<String, List<Shop>>  getShopCarbyUserid(String userid) {

        return mongodbDao.getShopCarbyUserid(userid);
    }

    @Override
    public   HashMap<String, List<Shop>> getShopCarbyCookieid(String cookieid) {

        return mongodbDao.getShopCarbyCookieid(cookieid);
    }

    @Override
    public Integer getShopCountMin(String shopid) {


        return shoppingcar.getShopCountMin(shopid);
    }




    public static void main(String[] args) {

      HashSet<Object> set = new HashSet<>();

        set.add("123");

        set.add("34");

        set.add("789");


        HashMap<String,List> map = new HashMap<>();

        List<Shop>  list  = new ArrayList<Shop>();
        Shop shop = new Shop();
        shop.setShopid("22222");
        shop.setShopcount(22222);
        shop.setShopname("22222");
        shop.setPrice("22222");
        list.add(shop);

        List<Shop>  list2  = new ArrayList<Shop>();
        Shop shop2 = new Shop();
        shop2.setShopid("333");
        shop2.setShopcount(333);
        shop2.setShopname("333");
        shop2.setPrice("333");
        list2.add(shop2);

        List<Shop>  list3  = new ArrayList<Shop>();
        Shop shop3 = new Shop();
        shop3.setShopid("444");
        shop3.setShopcount(444);
        shop3.setShopname("44");
        shop3.setPrice("444");
        list3.add(shop3);

        map.put("12",list);

        map.put("13",list2);

        map.put("12",list3);


     //   map.put(12,"555")
        Set<String> strings = map.keySet();

        Iterator<String> it = strings.iterator();

        HashMap<String,List> maps = new HashMap<>();

        // 则是判断当前元素是否存在，并指向下一个元素（即所谓的索引）
        while(it.hasNext()){
             // next 是返回当前元素， 并指向下一个元素。 key
            String key = it.next();
            //获取指定的value
            Object o = map.get(key);
            System.out.println(o+"---"+key);


        }


    }


}
